<?php
namespace app\admin\logic;
use app\admin\validate\IntegralOperate as IntegralOperateValidate;
use \PhpOffice\PhpSpreadsheet\Spreadsheet;
use \PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class IntegralTotalLogic extends BaseLogic {

    /**
     * 获取积分统计查询条件
     * @param $department
     * @param $username
     * @return array
     */
    public function get_search_it_maps($department,$username){
        $maps = [];
        $maps[] = ['role','>',1];

        if($department != '全部'){
            $u_maps = [];
            $u_maps[] = ['department','=',$department];
            $openids = model('user')->get_column($u_maps,'openid');
            $maps[] = ['openid','in',$openids];
        }

        if(!empty($username)){
            $u_maps = [];
            $u_maps[] = ['username','like','%' . $username . '%'];
            $openids = model('user')->get_column($u_maps,'openid');
            $maps[] = ['openid','in',$openids];
        }
        return $maps;
    }

    /**
     * 获取积分统计
     * @param $params
     * @return mixed
     */
    public function get_it($params){
        $maps = $this->get_search_it_maps($params['department'],$params['username']);
        $limit = ($params['page'] -1) * $params['rows'];

        $list = model('user')->get_list($maps,'id,openid,username,department,total_integral','total_integral desc','',$limit,$params['rows']);

        $total_num = model('user')->get_count($maps,'id');

        $data['list'] = $list;
        $data['total_num'] = $total_num;
        return $this->get_response(1,'OK',$data);
    }

    /**
     * 生成积分统计excel
     * @param $ExcelName
     * @param $data
     * @return bool
     */
    public function gen_it_excel($ExcelName,$data){
        if(count($data[0]) > 26){
            return $this->get_response(0,'导出excel最大列数为26，请缩减数据列数');
        }
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        for($row = 1;$row <= count($data);$row++){
            $index = 0;
            foreach($data[$row-1] as $k => $v) {
                $col = chr($index + 65);
                $cell = ($col . $row);
                $sheet->setCellValue($cell, $v);
                $index++;
            }
        }

        header('Content-Type: application/vnd.ms-excel;charset=utf8-general-ci');
        header('Content-Disposition: attachment;filename='.$ExcelName);
        header('Cache-Control: max-age=0');

        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');
        //$writer->save($ExcelName);
        return true;
    }

    /**
     * 积分操作规则
     * @param $params
     * @return mixed
     */
    public function check_integral_operate_rule($params){
        $validate = new IntegralOperateValidate();
        $r = $validate->scene('add')->check($params);
        if(!$r){
            return $this->get_response(0,$validate->getError());
        }
        return $this->get_response(1,'OK');
    }
}